/* components */
import {
  ConnectorModuleConnectorDialogDetailAction,
  ConnectorModuleConnectorDialogDetailActionQuery,
  ConnectorModuleConnectorDialogDetailActionCreate,
  ConnectorModuleConnectorDialogDetailColumn,
  ConnectorModuleConnectorDialogDetailHeader,
  ConnectorModuleConnectorDialogDetailSetting
} from '@src/modules/connector/components'
/* model */
import { 
  ActionReqOrResTypeEnum,
  AppTypeEnum,
  ConnectorActionEnum,
  ConnectorDefaultPassAppData, 
  ConnectorDialogDetailData, 
  ConnectorDialogDetailPaasData, 
  ConnectorField, 
  ConnectorModuleComponentNameEnum, 
  ConnectorOptionsAction, 
  ConnectorOptionsActionEnum, 
  ConnectorOptionsActionMappingFieldKeyEnum, 
  ConnectorOptionsActionTextEnum, 
  ConnectorToField 
} from '@src/modules/connector/model'
import { CardInputTypeEnum } from '@model/enum/CardEnum'
/* scss */
import '@src/modules/connector/components/connector-dialog-detail/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, PropType, ref, CreateElement } from 'vue'
import { CommonComponentInstance } from '@model/VC'
/* types */
import { ConnectorRuleFormItemType } from '@src/modules/connector/types'
/* utils */
import { message } from '@src/util/message'
import { cloneDeep, isArray, nth } from 'lodash'
import { checkIsExistAction, convertJsonFieldTypeToFieldList } from '@src/modules/connector/util/card'
import { createConnectorRuleFormItem, getShowFieldNameListByConnectorToFields } from '@src/modules/connector/util'
import { t } from '@src/locales'

export type ConnectorModuleConnectorDialogDetailProps = {
  value: ConnectorDialogDetailData;
  fromBizTypeName: string;
}

export interface ConnectorModuleConnectorDialogDetailSetupState {
  
}

export enum ConnectorModuleConnectorDialogDetailEmitEventNameEnum {
  Input = 'input',
}

export type ConnectorModuleConnectorDialogDetailInstance = ComponentInstance & ConnectorModuleConnectorDialogDetailSetupState
export type ConnectorModuleConnectorDialogDetailVM = ComponentRenderProxy<ConnectorModuleConnectorDialogDetailProps> & CommonComponentInstance & ConnectorModuleConnectorDialogDetailInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleConnectorDialogDetail,
  emits: [
    ConnectorModuleConnectorDialogDetailEmitEventNameEnum.Input,
  ],
  props: {
    value: {
      type: Object as PropType<ConnectorDialogDetailData>,
      default: () => ({})
    },
    fromBizTypeName: {
      type: String as PropType<string>,
      default: ''
    }
  },
  setup(props: ConnectorModuleConnectorDialogDetailProps, { emit }) {
    // 
  },
  computed: {
    // 执行动作列表
    actions(): ConnectorOptionsAction[] {
      return this.value.actionList || []
    },
    // 执行动作列表的当前选中值
    actionsValue(): ConnectorOptionsAction[] {
      return this.value?.actionsValue || []
    },
    insertRuleForms(): ConnectorRuleFormItemType[] {
      return this.value?.insertRuleForms || []
    },
    // paas 应用数据
    passApp(): ConnectorDialogDetailPaasData {
      return this.value?.paasApp || ConnectorDefaultPassAppData
    },
    // paas 应用数据 id
    passAppId(): string {
      return this.passApp?.id || ''
    },
    // paas 应用数据 图标
    passAppIcon(): string {
      return this.passApp?.icon || ''
    },
    // paas 应用数据 名称
    passAppName(): string {
      return this.passApp?.name || ''
    },
    selectRuleForms(): ConnectorRuleFormItemType[] {
      return this.value?.selectRuleForms || []
    },
    // 是否显示 查询动作
    showActionQuery(): boolean {
      return checkIsExistAction(this.actionsValue, ConnectorOptionsActionEnum.Select)
    },
    // 是否显示 创建动作
    showActionCreate(): boolean {
      return checkIsExistAction(this.actionsValue, ConnectorOptionsActionEnum.Insert)
    },
    toFieldList(): ConnectorToField[] {
      return this.value?.toFieldList || [];
    },
    selectActionItemToRequestFieldList():ConnectorToField[] {
      return this.getActionToFields(ConnectorOptionsActionEnum.Select, ActionReqOrResTypeEnum.ToResponseFieldList);
    },
    showFieldList():ConnectorToField[] {
      return this.selectActionItemToRequestFieldList.map(field => {
        let newItem = field;
        newItem.show = false;
        (this.value?.showFieldNameList || []).forEach(item=>{
          if(field.enName == item){
            newItem.show = true
          }
        })
        return newItem
      })
    },
    toBizTypeName(): string {
      return this.value?.paasApp?.name || '';
    },
    toBizTypeId(): string {
      return this.value?.paasApp?.id || ''
    },
    computedFieldList():ConnectorToField[] {
      return this.value?.additionalId ? this.showFieldList : this.selectActionItemToRequestFieldList || []
    },
    isOutsideApp(): boolean {
      return this.value?.appType === AppTypeEnum.OutSide
    },
    conditionalLimit(): string {
      return this.value?.conditionalLimit || '1';
    },
  },
  methods: {
    initialize() {
      // 
    },
    onValueInputHandler(value: ConnectorDialogDetailData) {
      this.$emit(ConnectorModuleConnectorDialogDetailEmitEventNameEnum.Input, value)
    },
    /** 
     * @description 连接器 执行动作选择 变化事件
    */
    onConnectorSelectActionInputHandler(value: ConnectorOptionsAction[]) {
      
      const newValue: ConnectorDialogDetailData = {
        ...this.value,
        actionsValue: value
      }

      // 存在相关查询的动作取消更新
      if(value.length > this.actionsValue.length) {
        const addOptionActionItem = nth(value, -1)
        const existSelect = this.actionsValue.some((item: ConnectorOptionsAction)=> item.action === addOptionActionItem?.action)
       
        if(existSelect && addOptionActionItem) return message.warning(t('common.connector.connectorModuleErrorMessageEnum.ConnectorSameAction', { action: ConnectorOptionsActionTextEnum[addOptionActionItem.action] as string }))
      }

      // 更新showFieldNameList
      const selectActionItem = value.find(item=> item.action === ConnectorOptionsActionEnum.Select)
      if(selectActionItem) {
        newValue.showFieldNameList = getShowFieldNameListByConnectorToFields(selectActionItem?.toResponseFieldList || [])
      }

      // 更新相关insertRuleForms插入动作的表单值
      const insertActionItem = value.find(item=> item.action === ConnectorOptionsActionEnum.Insert)
      if(insertActionItem && newValue.insertRuleForms.length === 0) {
        newValue.insertRuleForms = (insertActionItem?.toRequestFieldList || []).filter(field=> field.required).map(toField => {
          return createConnectorRuleFormItem(toField)
        })
      }

      this.onValueInputHandler(newValue)
      
    },
    /** 
     * @description 连接器 新建规则表单 变化事件
    */
    onConnectorInsertRuleFormInputHandler(value: ConnectorRuleFormItemType[]) {
      
      const newValue: ConnectorDialogDetailData = {
        ...this.value,
        insertRuleForms: value
      }
      
      this.onValueInputHandler(newValue)
      
    },
    /** 
     * @description 连接器 查询规则表单 变化事件
    */
    onConnectorSelectRuleFormInputHandler(value: ConnectorRuleFormItemType[]) {
      
      const newValue: ConnectorDialogDetailData = {
        ...this.value,
        selectRuleForms: value
      }
      
      this.onValueInputHandler(newValue)
      
    },
    /** 选择表单未选择值时处理 */
    onChangeCondition(val: any) {
      const newValue: ConnectorDialogDetailData = {
        ...this.value,
        conditionalLimit: val
      }
      this.onValueInputHandler(newValue)
    },
    /** 
     * @description 连接器 表单显示字段 变化事件
    */
    onConnectorShowFieldNameListInputHandler(value: string[]) {
      
      const newValue: ConnectorDialogDetailData = {
        ...this.value,
        showFieldNameList: value
      }
      
      this.onValueInputHandler(newValue)
      
    },
    /** 
     * @description 连接器 表单字段列表 变化事件
    */
    onConnectorToFieldListInputHandler(value: ConnectorToField[]) {
      
      const newValue: ConnectorDialogDetailData = {
        ...this.value,
      }

      // 由于相关toField取值修改修改更新相关动作里面的toResponseFieldList
      const selectActionItemIndex = newValue.actionsValue.findIndex(item=> item.action === ConnectorOptionsActionEnum.Select)
      if(selectActionItemIndex > -1) newValue.actionsValue[selectActionItemIndex].toResponseFieldList = value
      
      this.onValueInputHandler(newValue)
      
    },
    /** 
     * @description 连接器 附件组件添加次数 单次/多次 变化事件
    */
    onConnectorInputTypeValueChangeHandler(value: CardInputTypeEnum) {
      
      const newValue: ConnectorDialogDetailData = {
        ...this.value,
        inputType: value
      }
      
      this.onValueInputHandler(newValue)
      
    },
    /**
     * 获取actionList中toRequestFieldList或者toResponseFieldList
     * @param action 
     * @param key 
     */

    getActionToFields(action: ConnectorOptionsActionEnum, key: ActionReqOrResTypeEnum) {
      const actionItem = this.value.actionsValue.find(item=> item.action === action)
      if(actionItem) {
        const cloneToFields = cloneDeep(actionItem?.[key] || [])
        const resultField = key === ActionReqOrResTypeEnum.ToRequestFieldList ? convertJsonFieldTypeToFieldList(cloneToFields) : cloneToFields
        return resultField
      }
      return []
    }
  },
  mounted() {
    this.initialize()
  },
  render(h: CreateElement) {
    return (
      <div class={ConnectorModuleComponentNameEnum.ConnectorModuleConnectorDialogDetail}>
        
        {/* start 头部 关联应用显示 */}
        <ConnectorModuleConnectorDialogDetailHeader
          icon={this.passAppIcon}
          name={this.passAppName}
        />
        {/* end 头部 关联应用显示 */}

        {/* start 执行动作 */}
        <ConnectorModuleConnectorDialogDetailAction 
          actions={this.actions}
          value={this.actionsValue}
          onInput={this.onConnectorSelectActionInputHandler}
        />
        {/* end   执行动作 */}

        {/* start 表单显示字段 */}
        <ConnectorModuleConnectorDialogDetailColumn 
          v-show={this.showActionQuery}
          columns={this.computedFieldList}
          onInput={this.onConnectorShowFieldNameListInputHandler}
          onChange={this.onConnectorToFieldListInputHandler}
        />
        {/* end 表单显示字段 */}
        
        {/* start 查询条件 */}
        {/* 这里的toFieldList传参是以前的toFieldList返回的结构但是现在后端过滤过了 直接从toRequestFieldList取所以传入就是这个toRequestFieldList（因为不想改props传值的key） */}
        <ConnectorModuleConnectorDialogDetailActionQuery 
          v-show={this.showActionQuery}
          value={this.selectRuleForms}
          toFieldList={this.getActionToFields(ConnectorOptionsActionEnum.Select, ActionReqOrResTypeEnum.ToRequestFieldList)} 
          fromFieldList={this.value.fromFieldList}
          fromBizTypeName={this.fromBizTypeName}
          toBizTypeName={this.toBizTypeName}
          onInput={this.onConnectorSelectRuleFormInputHandler}
          onChangeCondition={this.onChangeCondition}
          isShowCondition={true}
          conditionalLimit={this.conditionalLimit}
        />
        {/* end   查询条件 */}
        
        {/* start 新建规则 */}
        {/* 这里的toFieldList传参是以前的toFieldList返回的结构但是现在后端过滤过了 直接从toRequestFieldList取所以传入就是这个toRequestFieldList（因为不想改props传值的key） */}
        <ConnectorModuleConnectorDialogDetailActionCreate 
          v-show={this.showActionCreate}
          value={this.insertRuleForms}
          toFieldList={this.getActionToFields(ConnectorOptionsActionEnum.Insert, ActionReqOrResTypeEnum.ToRequestFieldList)} 
          fromFieldList={this.value.fromFieldList}
          fromBizTypeName={this.fromBizTypeName}
          toBizTypeName={this.toBizTypeName}
          toBizTypeId={this.toBizTypeId}
          inputTypeValue={this.value.inputType}
          showDetailType={!this.isOutsideApp}
          onInput={this.onConnectorInsertRuleFormInputHandler}
          onInputTypeValueChange={this.onConnectorInputTypeValueChangeHandler}
        />
        {/* start 新建规则 */}
        
        {/* start 规则设置 */}
        <ConnectorModuleConnectorDialogDetailSetting />
        {/* end 规则设置 */}
        
      </div>
    )
  }
})
